﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SumiaAccountBook
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
            this.addSubControl(new SubControls.UCCashFlow());
        }        

        /// <summary>
        /// 关闭操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Close_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        /// <summary>
        /// 导入历史数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Import_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new OpenFileDialog();
            dialog.Title = "请选择CSV文件";
            dialog.Filter = "CSV文件(*.csv)|*.csv|所有文件(*.*)|*.*";

            //允许多选
            dialog.Multiselect = false;
            if (true == dialog.ShowDialog(this))
            {
                DataTable dt = OpenCSV(dialog.FileName);
                if (null == dt || dt.Rows.Count <= 0)
                {
                    MessageBox.Show("未读取到任何内容！");
                }

                List<DataAccess.Entity.CashFlow> list = new List<DataAccess.Entity.CashFlow>();
                int accountBookId = 2;  //这块暂时写死了
                int stafId = -1;
                int type,category,projectId;
                decimal amount;
                DateTime date;
                string memo;
                Biz.KVProject kvProject = new Biz.KVProject();
                Biz.KVKeyValue kv = new Biz.KVKeyValue();
                Biz.KVStaff kvStaff = new Biz.KVStaff();
                foreach(DataRow row in dt.Rows)
                {
                    type = Biz.KVConstHelper.GetInstance().GetKey<Biz.KVCashFlowType>(row[0].ToString());
                    category = kv.GetKey(row[1].ToString());
                    if(category<0)
                    {
                        MessageBox.Show("未知的类别：" + row[1].ToString());
                        return;
                    }
                    amount = Convert.ToDecimal(row[2].ToString());
                    date = Convert.ToDateTime(row[3].ToString());
                    projectId = -1;
                    if (!string.IsNullOrEmpty(row[4].ToString()))
                    {
                        projectId = kvProject.GetKey(row[4].ToString());
                        if (projectId < 0)
                        {
                            MessageBox.Show("未知的项目：" + row[4].ToString());
                            return;
                        }
                    }
                    if (!string.IsNullOrEmpty(row[5].ToString().Trim()))
                    {
                        stafId = kvStaff.GetKey(row[5].ToString().Trim());
                    }
                    else
                    {
                        stafId = -1;
                    }
                    
                    memo = row[6].ToString().Trim();
                    list.Add(
                        new DataAccess.Entity.CashFlow { Type = type, Category = category, Amount = amount, Date = date, ProjectId = projectId, StaffId = stafId, AccountBookId = accountBookId, Memo = memo });
                }
                DataAccess.DaCommonADO.InsertBatch(list);
            }
        }

        /// <summary>
        /// 将CSV文件的数据读取到DataTable中
        /// </summary>
        /// <param name="fileName">CSV文件路径</param>
        /// <returns>返回读取了CSV数据的DataTable</returns>
        private static DataTable OpenCSV(string filePath)
        {
            DataTable dt = new DataTable();
            using (FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                using (StreamReader sr = new StreamReader(fs, GetFileEncodeType(filePath)))
                {
                    //记录每次读取的一行记录
                    string strLine = "";
                    //记录每行记录中的各字段内容
                    string[] aryLine = null;
                    //标示列数
                    int columnCount = 7;
                    //标识行数
                    int rowCount = 0;

                    //逐行读取CSV中的数据
                    while ((strLine = sr.ReadLine()) != null)
                    {
                        rowCount++;                        
                        if (1 == rowCount)  //表头
                        {
                            //创建列
                            for (int i = 0; i < columnCount; i++)
                            {
                                DataColumn dc = new DataColumn();
                                dt.Columns.Add(dc);
                            }
                        }
                        else
                        {
                            aryLine = strLine.Split(',');
                            if (null != aryLine && aryLine.Length >= columnCount)
                            {
                                DataRow dr = dt.NewRow();
                                for (int j = 0; j < columnCount; j++)
                                {
                                    dr[j] = aryLine[j].Trim();
                                }
                                dt.Rows.Add(dr);
                            }
                        }
                    }

                }
            }
            return dt;
        }

        /// <summary>
        /// 打开流水账
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Journal_Click(object sender, RoutedEventArgs e)
        {
            this.addSubControl(new SubControls.UCCashFlow());
        }

        /// <summary>
        /// 往来账
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Current_Click(object sender, RoutedEventArgs e)
        {
            this.addSubControl(new SubControls.UCCurrent());
        }

        /// <summary>
        /// 项目管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Project_Click(object sender, RoutedEventArgs e)
        {
            this.addSubControl(new SubControls.ucProject());
        }

        /// <summary>
        /// 人员管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Staff_Click(object sender, RoutedEventArgs e)
        {
            this.addSubControl(new SubControls.ucStaff());
        }

        /// <summary>
        /// 账本
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Book_Click(object sender, RoutedEventArgs e)
        {
            this.addSubControl(new SubControls.ucAccountBook());
        }

        /// <summary>
        /// 设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Config_Click(object sender, RoutedEventArgs e)
        {
            this.addSubControl(new SubControls.ucConfig());
        }

        /// <summary>
        /// 关于
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void About_Click(object sender, RoutedEventArgs e)
        {
            SubControls.WinAbout winAbout = new SubControls.WinAbout();
            winAbout.ShowDialog();
        }

        /// <summary>
        /// 添加子控件
        /// </summary>
        /// <param name="uc"></param>
        private void addSubControl(UserControl uc)
        {
            if (this.wpContent.Children.Count > 0)
            {
                this.wpContent.Children.RemoveAt(0);
            }
            this.wpContent.Children.Add(uc);
        }


        /// <summary>
        /// 判断文本文件的编码格式
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        private static System.Text.Encoding GetFileEncodeType(string filename)
        {
            using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                using (System.IO.BinaryReader br = new System.IO.BinaryReader(fs))
                {
                    Byte[] buffer = br.ReadBytes(2);
                    if (buffer[0] >= 0xEF)
                    {
                        if (buffer[0] == 0xEF && buffer[1] == 0xBB)
                        {
                            return System.Text.Encoding.UTF8;
                        }
                        else if (buffer[0] == 0xFE && buffer[1] == 0xFF)
                        {
                            return System.Text.Encoding.BigEndianUnicode;
                        }
                        else if (buffer[0] == 0xFF && buffer[1] == 0xFE)
                        {
                            return System.Text.Encoding.Unicode;
                        }
                        else
                        {
                            return System.Text.Encoding.Default;
                        }
                    }
                    else
                    {
                        return System.Text.Encoding.Default;
                    }
                }
            }
        }

        private void ByProject_Click(object sender, RoutedEventArgs e)
        {
            this.addSubControl(new SubControls.UCSearch_ByProject());
        }

        private void ByStaff_Click(object sender, RoutedEventArgs e)
        {
            this.addSubControl(new SubControls.UCSearch_ByStaff());
        }

        private void ByDate_Click(object sender, RoutedEventArgs e)
        {
            this.addSubControl(new SubControls.UCSearch_ByDate());
        }

        private void ByShared_Click(object sender, RoutedEventArgs e)
        {
            this.addSubControl(new SubControls.UCSearch_ByShare());
        }

        private void Contact_Click(object sender, RoutedEventArgs e)
        {
            var diag = new SubControls.WinContact();
            diag.ShowDialog();
        }

        private void Donate_Click(object sender, RoutedEventArgs e)
        {
            var diag = new SubControls.WinDonate();
            diag.ShowDialog();
        }
    }
}
